import axios from 'axios'
const CancelToken = axios.CancelToken;
import store from '../store'
import * as types from '../store/action-type'
class HttpRequest {
  constructor() {
    this.baseURL = process.env.NODE_ENV === 'production' ? '/' : 'http://127.0.0.1:7001'
    this.timeout = 3000;
    this.queue = {}; // 用来维护请求队列
  }
  setInterceptor(instance, url) {
    instance.interceptors.request.use((config) => {
      this.queue[url] = true;
      if (Object.keys(this.queue).length === 0) { // 多个请求只有第一个请求的时候才开启loading
        // todo 开启loading效果
      }
      const token = localStorage.getItem('token');
      if (token) {
        // 如果本地存储有Token，则在headers里面携带token
        config.headers.authorization = token;
      }
      config.cancelToken = new CancelToken(function(p1){
        //p1就是取消函数
        store.commit(types.SET_REQUEST_TOKEN, p1);
      })
      return config;
    });
    instance.interceptors.response.use((config) => {
      delete this.queue[url];
      if (!Object.keys(this.queue).length) {
        // todo 关闭loading效果
      }
      if (config.data.err === 0 ) {
        return config.data.data;
      } else {
        return Promise.reject(config.data);
      }
    }, (error) => {
      delete this.queue[url];
      if (!Object.keys(this.queue).length) {
        // todo 关闭loading效果
      }
      return Promise.reject(error);
    })
  }
  request(options) {
    let config = {
      baseURL: this.baseURL,
      timeout: this.timeout,
      ...options
    }
    let instance = axios.create();
    this.setInterceptor(instance, options.url)
    return instance(config) // 产生一个promise实例
  }
  get(url, data={}) {
    // axios.get(url, {
    //  params: {}
    // })
    return this.request({
      url,
      method : 'GET',
      ...data
    })
  }
  post(url, data={}) {
    // axios.post(url, {data})
    return this.request({
      url,
      method : 'POST',
      data
    })
  }
}

export default new HttpRequest()